package com.pangus.ims.apiRm.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.pangus.common.dto.ApiRequest;
import com.pangus.common.dto.ApiResponse;
import com.pangus.common.dto.EditDataResult;
import com.pangus.common.sys.dto.domain.LogDto;
import com.pangus.common.sys.service.ParameterService;
import com.pangus.common.sys.utils.CheckUtils;
import com.pangus.common.sys.utils.DateUtils;
import com.pangus.common.sys.utils.SqlQueryUtils;
import com.pangus.error.exception.BaseException;
import com.pangus.fa.i18n.FaMessageSource;
import com.pangus.fa.mybatis.mapper.entity.Condition;
import com.pangus.fa.mybatis.mapper.entity.Condition.Criteria;
import com.pangus.fa.util.FastIdUtils;
import com.pangus.ims.apiRm.WmsRmApiConstants;
import com.pangus.ims.apiRm.dto.WmsApiRequestCount;
import com.pangus.ims.apiRm.dto.WmsResponseCommonForm;
import com.pangus.ims.bs.dto.domain.BsMtrlDto;
import com.pangus.ims.bs.dto.domain.BsPhaseDto;
import com.pangus.ims.bs.dto.domain.BsWplanDto;
import com.pangus.ims.bs.form.BsWplanForm;
import com.pangus.ims.bs.service.BsMtrlService;
import com.pangus.ims.bs.service.BsPhaseService;
import com.pangus.ims.bs.service.BsWplanService;
import com.pangus.ims.wms.WmsConstants;
import com.pangus.ims.wms.service.WmsApiRequestCountService;

@Service
public class WmsMoGetDataApiServiceTask extends WmsCommonGetDataApiService<BsWplanForm>
		implements WmsRmReturnData<BsWplanForm> {

    private final Logger logger = LoggerFactory.getLogger(WmsMoGetDataApiServiceTask.class);
//	@Autowired
//	private WmsRmSendAndGetDataApiService rmSendAndGetDataApiService;

	@Autowired
	private BsWplanService bsWplanService;

	@Autowired
	private BsMtrlService bsMtrlService;

	@Autowired
	private FaMessageSource messageSource;

	@Autowired
	private WmsBomGetDataApiServiceTask wmsBomGetDataApiService;

//	@Log
//	protected Logger logger;

	@Autowired
	private ParameterService parameterService;
	
	@Autowired
	private WmsApiRequestCountService wmsApiRequestCountService;

	@Autowired
	private WmsOrderMtrlGetDataApiService wmsOrderMtrlGetDataApiService;
	
	@Autowired
	private SqlQueryUtils sqlUtils;
	
	@Autowired
	private BsPhaseService bsPhaseService;
	
	@Autowired
	private FastIdUtils fastIdUtils;
	
	@Autowired
	private WmsGlobalStrategyOrgIdService wmsGlobalStrategyOrgIdService;
	
	public static ExecutorService es = new ThreadPoolExecutor(20, 30, 10L, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),
			new ThreadPoolExecutor.DiscardPolicy());

	public ApiResponse<List<BsWplanForm>> getData(ApiRequest<Map<String, String>> apiRequest) {
//		String docType = WmsRmApiConstants.DOC_TYPE.GET_ORDER;
		Map<String, String> map = new HashMap<String, String>();
		map.put("START_DATE", apiRequest.getData().get("START_DATE"));
		map.put("END_DATE", apiRequest.getData().get("END_DATE"));
		map.put("ORG_ID", apiRequest.getData().get("ORG_ID"));
//		ApiResponse<List<WmsResponseCommonForm>> sourceApiResponse = rmSendAndGetDataApiService.getDate(docType, map);
		ApiResponse<List<WmsResponseCommonForm>> sourceApiResponse = this.dbLinkGetData(map);
		ApiResponse<List<BsWplanForm>> apiResponse = getResponse(apiRequest, sourceApiResponse, this, map);
		return apiResponse;
	}

	/*
	 *  接口优化
	 *  通过dblink方式获取EBS视图数据, 不通过webservic方式
	 * by zpc on 2022.3.9
	 */
	public ApiResponse<List<WmsResponseCommonForm>> dbLinkGetData(Map<String, String> map){
		logger.info("===>dblink自动获取工单"+map);
		String startDate = map.get("START_DATE");
		String endDate = map.get("END_DATE");
		String orgId = map.get("ORG_ID");
		String sql = "select m.* from apps.cux_wip_order_v@EBSDBLINK m where 1=1 and m.ORG_ID = '"+ orgId +"' ";
		if(StringUtils.isNotBlank(startDate)) {
			sql += "  AND m.LAST_UPDATE_DATE >=  TO_DATE('"+startDate+"', 'YYYYMMDDHH24MI') ";
		}
		
		if(StringUtils.isNotBlank(endDate)) {
			sql += "  AND m.LAST_UPDATE_DATE <=  TO_DATE('"+endDate+"', 'YYYYMMDDHH24MI') ";
		}
		ApiResponse<List<WmsResponseCommonForm>> sourceApiResponse = new ApiResponse<List<WmsResponseCommonForm>>();
		sourceApiResponse.setResultCode("S1001000");
		if(startDate==null&&endDate==null) {
			sourceApiResponse.setData(null);
			return sourceApiResponse ;
		}
		
		List<WmsResponseCommonForm> resultList = null;
		try {
			resultList = sqlUtils.dbLinkQueryAll(sql, null, WmsResponseCommonForm.class);
		}catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("dblink数据库异常！");
		}
		logger.info("查询结果"+(resultList == null?"0":resultList.size()));
		logger.info("内容:");
		if(resultList != null && resultList.size() > 0) {
			resultList.stream().forEach(l -> logger.info(l.toString()));
		}
		sourceApiResponse.setData(resultList);
		return sourceApiResponse;
	}
	
	// 转实体
	@Override
	public List<BsWplanForm> toData(List<WmsResponseCommonForm> list, Map<String, String> resultMap) {
		CheckUtils checkUtils = new CheckUtils(messageSource, parameterService, new LogDto());
		List<BsWplanForm> moList = new ArrayList<BsWplanForm>();
		CountDownLatch countDownLatch = new CountDownLatch(list.size());
		logger.info("list.size():" + list.size());
		for (WmsResponseCommonForm responseCommonForm : list) {
			es.execute(new Runnable() {
				@Override
				public void run() {
					threadGetData(responseCommonForm, checkUtils, moList, countDownLatch);
				}
			});
		}
		try {
			countDownLatch.await();
		} catch (Exception e) {
			logger.info(e.toString());
		}
		return moList;
	}

	public void threadGetData(WmsResponseCommonForm responseCommonForm, CheckUtils checkUtils, List<BsWplanForm> moList,
			CountDownLatch countDownLatch) {
		logger.info("countDownLatch.toString():" + countDownLatch.toString());
		logger.info("工单操作开始 : " + responseCommonForm.getERP_MO());
		logger.info("工单ERP_ID : " + responseCommonForm.getERP_ID());
		logger.info("工单信息 : " + JSONObject.toJSONString(responseCommonForm));
		try {
			
//			if (StringUtils.isNotBlank(responseCommonForm.getERP_MO())
//					&& ( responseCommonForm.getERP_MO().startsWith("EM")
//							|| responseCommonForm.getERP_MO().startsWith("EP"))) {
//				countDownLatch.countDown();
//				return;
//			}
//			if (StringUtils.isNotBlank(responseCommonForm.getERP_STATUS())
//					&& !WmsRmApiConstants.ERP_MO_STATUS.YES.equals(responseCommonForm.getERP_STATUS())) {
//				// 单据在ERP必须是已释放状态才能获取;
//				countDownLatch.countDown();
//				return;
//			}
			if(StringUtils.isNotBlank(responseCommonForm.getERP_STATUS()) && !WmsRmApiConstants.ERP_MO_STATUS.YES.equals(responseCommonForm.getERP_STATUS()) && !"Released".equals(responseCommonForm.getERP_STATUS())) {
				//单据在ERP必须是已释放状态才能获取;
				System.out.println("单据在ERP必须是已释放状态才能获取");
				countDownLatch.countDown();
				return;
			}
			if (WmsConstants.WMSDTO_DEFAULT_YES.equals(responseCommonForm.getIS_OUTS())) {
				// 委外订单不获取
				System.out.println("委外订单不获取");
				countDownLatch.countDown();
				return;
			}
			
			if(StringUtils.isBlank(responseCommonForm.getJOB_TYPE())) {
				System.out.println("ERP工单类型："+responseCommonForm.getERP_MO()+"工单类型为空拉取失败！");
				logger.info("ERP工单类型："+responseCommonForm.getERP_MO()+"工单类型为空拉取失败！");
				countDownLatch.countDown();
				return;
			}
			
			
			BsWplanForm bsWplanForm = new BsWplanForm();
			bsWplanForm.setWplanId(responseCommonForm.getERP_MO() + "_FA");// 主计划代码
			bsWplanForm.setWplanCode(responseCommonForm.getERP_MO() + "_FA");// 主计划编码
			bsWplanForm.setErpMo(responseCommonForm.getERP_MO());// ERP工单编码
			bsWplanForm.setErpId(responseCommonForm.getERP_ID());// ERP工单ID
			logger.info("自动同步时间："+responseCommonForm.getLAST_UPDATE_DATE());
			bsWplanForm.setLastUpdateDate(responseCommonForm.getLAST_UPDATE_DATE());//最新更新时间
			
			BsWplanDto isExist = new BsWplanDto();
			isExist.setWplanId(bsWplanForm.getWplanId());
			isExist.setWplanStat(1);
			isExist = bsWplanService.selectFirst(isExist);
			if(isExist != null) {
				System.out.println("已存在主计划WplanId：" + bsWplanForm.getWplanId());
				countDownLatch.countDown();
				return;
			}
			
			bsWplanForm.setOrgCode(responseCommonForm.getORG_CODE());
			bsWplanForm.setSupId(responseCommonForm.getSUP_ID());// 供应商编码
			bsWplanForm.setOrgId(responseCommonForm.getORG_ID());// 库存组织ID
			System.out.println("===============CLASS_CODE:接收的==================");
			System.out.println(responseCommonForm.getCLASS_CODE());
			System.out.println("===============CLASS_CODE==================");
			bsWplanForm.setClassCode(responseCommonForm.getCLASS_CODE());
			bsWplanForm.setBomVer(responseCommonForm.getBOM_VERSION());
			BsMtrlDto bsMtrlDto = new BsMtrlDto();
			bsMtrlDto.setOrgId(responseCommonForm.getORG_ID());
			bsMtrlDto.setMtrlCode(responseCommonForm.getPROD_ID());
			bsMtrlDto = bsMtrlService.selectFirst(bsMtrlDto);
			if (bsMtrlDto == null) {
				countDownLatch.countDown();
				logger.info("ERP物料未定义", new BaseException());
				return ;
			} else {
				bsWplanForm.setProdId(bsMtrlDto.getMtrlId());// 成品编码
				if(!"Y".equals(responseCommonForm.getZG_FLAG())) {//不是整改工单才同步bom
					// 判断成品BOM信息是否存在
					// 不存在时候获取对应成品BOM
					HashMap<String, String> bomMap = new HashMap<String, String>();
					bomMap.put("ORG_ID", bsMtrlDto.getOrgId());
					bomMap.put("PROD_ID", bsMtrlDto.getMtrlCode());
					ApiRequest<Map<String, String>> bomApiRequest = new ApiRequest<Map<String, String>>();
					bomApiRequest.setData(bomMap);
					wmsBomGetDataApiService.getData(bomApiRequest);
				}
			}

			bsWplanForm.setPQty(new BigDecimal(responseCommonForm.getP_QTY()));// 计划数量
			bsWplanForm.setIsOuts(responseCommonForm.getIS_OUTS());// 是否外协工单
			bsWplanForm.setLastwpOuts(responseCommonForm.getLASTWP_OUTS());// 末工序是否委外
			bsWplanForm.setPbDate(DateUtils.convertStringToDate("yyyyMMddHHmmss", responseCommonForm.getPB_DATE()));
			bsWplanForm.setPeDate(DateUtils.convertStringToDate("yyyyMMddHHmmss", responseCommonForm.getPE_DATE()));
			bsWplanForm.setCpx(responseCommonForm.getCPX());//产品线
			bsWplanForm.setOaNum(responseCommonForm.getOA_NUM());// oa电子流
			bsWplanForm.setSaleOrder(responseCommonForm.getSO_NO());// 销售订单号
			
			//增加对CKD工单的判断
			if(StringUtils.equalsIgnoreCase("CKD", responseCommonForm.getCLASS_CODE()) || 
					StringUtils.equalsIgnoreCase("CKD-SL", responseCommonForm.getCLASS_CODE()) 
					|| StringUtils.equalsIgnoreCase("G-Trade", responseCommonForm.getCLASS_CODE()) ) {
				System.out.println("CKD,CKD-SL,G-Trade工单，CLASS_CODE:" + responseCommonForm.getCLASS_CODE() + ",默认工艺段FIMSGYD");
			    //对用CKD工单组织非IMS工艺段从数据库获取。没有就自动新增一个。
				BsPhaseDto pDto = new BsPhaseDto();
				pDto.setPhaseCode("FIMSGYD");
				pDto.setOrgId(responseCommonForm.getORG_ID());
				pDto = bsPhaseService.selectOne(pDto);
				logger.info("工单手动接口是否存在非IMS工艺段："+responseCommonForm.getORG_ID()+"pDto:"+pDto);
				if(pDto!=null) {
					bsWplanForm.setPhaseId(pDto.getPhaseId());
				}else {
					BsPhaseDto pDtoNew = new BsPhaseDto();
					pDtoNew.setPhaseId(fastIdUtils.nextId());
					pDtoNew.setCreatedBy("X299841286054154240");
					pDtoNew.setCreatedDate(new Date());
					pDtoNew.setUpdatedBy("X299841286054154240");
					pDtoNew.setUpdatedDate(new Date());
					pDtoNew.setPhaseCode("FIMSGYD");
					pDtoNew.setPartnerCode("PGPG");
					pDtoNew.setOrgId(responseCommonForm.getORG_ID());
					pDtoNew.setPhaseType(3);
					pDtoNew.setCalResType(1);
					pDtoNew.setIsValid("Y");
					pDtoNew.setPhaseName("非IMS工艺段");
				    int count = bsPhaseService.insert(pDtoNew);
				    if(count<=0) {
				    	checkUtils.throwException("ERP物料未定义", new BaseException());
				    }
					bsWplanForm.setPhaseId(pDtoNew.getPhaseId());// 工艺段代码
				}												
				
			} else {
				System.out.println("非CKD,CKD-SL工单,G-Trade，CLASS_CODE:" + responseCommonForm.getCLASS_CODE() + ",默认工艺段TYGYD");
			    //对用工单组织通用工艺段从数据库获取。没有就自动新增一个。
				BsPhaseDto pDto = new BsPhaseDto();
				pDto.setPhaseCode("TYGYD");
				pDto.setOrgId(responseCommonForm.getORG_ID());
				pDto = bsPhaseService.selectOne(pDto);
				logger.info("工单手动接口是否存在通用工艺段："+responseCommonForm.getORG_ID()+"pDto:"+pDto);
				if(pDto!=null) {
					bsWplanForm.setPhaseId(pDto.getPhaseId());
				}else {
					BsPhaseDto pDtoNew = new BsPhaseDto();
					pDtoNew.setPhaseId(fastIdUtils.nextId());
					pDtoNew.setCreatedBy("X299841286054154240");
					pDtoNew.setCreatedDate(new Date());
					pDtoNew.setUpdatedBy("X299841286054154240");
					pDtoNew.setUpdatedDate(new Date());
					pDtoNew.setPhaseCode("TYGYD");
					pDtoNew.setPartnerCode("PGPG");
					pDtoNew.setOrgId(responseCommonForm.getORG_ID());
					pDtoNew.setPhaseType(1);
					pDtoNew.setCalResType(1);
					pDtoNew.setIsValid("Y");
					pDtoNew.setPhaseName("通用工艺段");
				    int count = bsPhaseService.insert(pDtoNew);
				    if(count<=0) {
				    	checkUtils.throwException("ERP物料未定义", new BaseException());
				    }
					bsWplanForm.setPhaseId(pDtoNew.getPhaseId());// 工艺段代码
				}		
			}
			
			
			bsWplanForm.setMoType(0);// 工单类型
			if(responseCommonForm.getJOB_TYPE().equals("3")) {
				bsWplanForm.setMoType(1);// 工单类型返工
			}else if(responseCommonForm.getJOB_TYPE().equals("1")) {
				bsWplanForm.setMoType(0);// 工单类型量产
			}else {
				logger.info("ERP工单类型为："+responseCommonForm.getJOB_TYPE()+"拉取失败");
				countDownLatch.countDown();
				return;
			}
			
			bsWplanForm.setWplanStat(0);// 主计划状态
			bsWplanForm.setIsBonded("N");
			bsWplanForm.setUpdatedBy("super_admin");
			bsWplanForm.setUpdatedDate(new Date());
			bsWplanForm.setPartnerCode("PGPG");

			BsWplanDto bsWplanDtoTemp = new BsWplanDto();
			bsWplanDtoTemp.setWplanId(bsWplanForm.getWplanId());
			bsWplanDtoTemp = bsWplanService.selectFirst(bsWplanDtoTemp);
			if (bsWplanDtoTemp == null) {
				bsWplanForm.setCreatedBy("super_admin_auto");
				bsWplanForm.setCreatedDate(new Date());
				bsWplanForm.setUpdatedBy("super_admin");
				bsWplanForm.setUpdatedDate(new Date());
				//bsWplanForm.setBsWplanEx7(new Date());
				System.out.println("============插入主计划信息（bsWplanForm）===========");
				JSONObject.toJSONString(bsWplanForm);
				System.out.println("============插入主计划信息（bsWplanForm）===end========");
				bsWplanService.insert(bsWplanForm);
			} else {
				BigDecimal oldPQty = bsWplanDtoTemp.getPQty();// 更新之前的计划数量
				
				
				//如果主计划导入更新过时间，将以导入过的为准
				if(bsWplanDtoTemp.getBsWplanEx9()!=null) {
					bsWplanDtoTemp.setPbDate(bsWplanDtoTemp.getPbDate());
					bsWplanDtoTemp.setPeDate(bsWplanDtoTemp.getPeDate());
				}else {
					bsWplanDtoTemp.setPbDate(bsWplanForm.getPbDate());
					bsWplanDtoTemp.setPeDate(bsWplanForm.getPeDate());
				}
				bsWplanDtoTemp.setPQty(bsWplanForm.getPQty());
				bsWplanDtoTemp.setUpdatedBy("super_admin_auto");
				bsWplanDtoTemp.setUpdatedDate(new Date());
				bsWplanDtoTemp.setLastUpdateDate(responseCommonForm.getLAST_UPDATE_DATE());
				//bsWplanForm.setBsWplanEx7(new Date());

				//如果存在已经下达了的主计划，直接跳过
				Condition conditionExists = new Condition(BsWplanDto.class);
				Criteria criteriaExists = conditionExists.createCriteria();
				criteriaExists.andNotEqualTo("wplanId", bsWplanDtoTemp.getWplanId());
				//criteriaExists.andEqualTo("erpMo", bsWplanDtoTemp.getErpMo());
				criteriaExists.andLike("wplanCode", ""+bsWplanDtoTemp.getErpMo()+"%");
				criteriaExists.andEqualTo("wplanStat", 1);
				List<BsWplanDto> otherListExists= bsWplanService.selectByCondition(conditionExists);
				if (otherListExists != null && otherListExists.size() > 0) {
					logger.info("已下达的计划不允许再操作 : " + otherListExists.get(0).getWplanCode()+"状态："+otherListExists.get(0).getWplanStat());
					countDownLatch.countDown();
					return;
				}
				bsWplanService.updateByPrimaryKey(bsWplanDtoTemp);
				// 更新主计划 : 主要为了更新拆分后生成的其它计划开始时间和计划结束时间
				Condition condition = new Condition(BsWplanDto.class);
				Criteria criteria = condition.createCriteria();
				criteria.andNotEqualTo("wplanId", bsWplanDtoTemp.getWplanId());
				criteria.andEqualTo("erpMo", bsWplanDtoTemp.getErpMo());
				criteria.andEqualTo("wplanStat", 0);// 未下达
				List<BsWplanDto> otherList = bsWplanService.selectByCondition(condition);
				if (otherList != null && otherList.size() > 0) {
					for (BsWplanDto wplan : otherList) {
						wplan.setLastUpdateDate(wplan.getLastUpdateDate());
						//更新计划开始结束时间
						if(wplan.getBsWplanEx9()!=null) {
							wplan.setPbDate(wplan.getPbDate());
							wplan.setPeDate(wplan.getPeDate());
						}else {
							wplan.setPbDate(bsWplanForm.getPbDate());
							wplan.setPeDate(bsWplanForm.getPeDate());
						}
						bsWplanService.updateByPrimaryKey(wplan);
					}
				}
				// 如果主计划的计划数量改变了,考虑计划要重新拆分!!!如果计划已经下单 这里有异常!!!!!
				if (bsWplanForm.getPQty().compareTo(oldPQty) != 0) {
					ApiRequest<Map<String, String>> apiRequestForSpilt = new ApiRequest<Map<String, String>>();
					Map<String, String> mapForSpilt = new HashMap<String, String>();
					mapForSpilt.put("ORG_ID", bsWplanForm.getOrgId());
					mapForSpilt.put("ERP_MO", bsWplanForm.getErpMo());
					mapForSpilt.put("ERP_ID", responseCommonForm.getERP_ID());
					apiRequestForSpilt.setData(mapForSpilt);
					wmsOrderMtrlGetDataApiService.getData(apiRequestForSpilt);// 重新拆分
				}
			}
			
			logger.info("查询物料 : " + responseCommonForm.getERP_MO());
			
			//同步工单物料
			ApiRequest<Map<String, String>> apiRequestForMtrl = new ApiRequest<Map<String, String>>();
			Map<String, String> mapForMoMtrl = new HashMap<String, String>();
			mapForMoMtrl.put("ORG_ID", bsWplanForm.getOrgId());
			mapForMoMtrl.put("ERP_MO", bsWplanForm.getErpMo());
			mapForMoMtrl.put("ERP_ID", responseCommonForm.getERP_ID());
			apiRequestForMtrl.setData(mapForMoMtrl);
			wmsOrderMtrlGetDataApiService.getData(apiRequestForMtrl);
			logger.info("工单操作结束 : " + responseCommonForm.getERP_MO());
			
			moList.add(bsWplanForm);
			countDownLatch.countDown();
		} catch (Exception e) {
			e.printStackTrace();
			countDownLatch.countDown();
		}

	}

	// 无参数请求, 默认请求102组织（锐明电子）下
	public EditDataResult<String> getData(EditDataResult<String>  resutData ) {
		int count = 0;
		//logger.info("每10分钟同步工单开始,按时间批次:");
//		String docType = WmsRmApiConstants.DOC_TYPE.GET_ORDER;
		Map<String, String> map = new HashMap<String, String>();
		Set<String> orgIds = wmsGlobalStrategyOrgIdService.listOrgIds(WmsConstants.GlobalStrategy.configName.DOCK_ERP_MO.toString());
		if(orgIds.isEmpty()) {
			logger.info("机构为空，不定时拉取工单数据");
			resutData.setCount(0);
			return resutData;
		}
		logger.info("定时同步工单数据："+JSONObject.toJSONString(orgIds));
		WmsApiRequestCount apiRequestDto = wmsApiRequestCountService.selectByPrimaryKey(new WmsApiRequestCount("123456"));
		Date updatedDate = apiRequestDto.getUpdatedDate();
		LocalDateTime startDate = LocalDateTime.ofInstant(updatedDate.toInstant(), ZoneId.systemDefault());
		LocalDateTime endDate = startDate.plusMinutes(30);
		DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
		LocalDateTime now = LocalDateTime.now();
		//String[] orgList = {"102"};//同步102（锐明电子）, 642组织（锐明电子（外单））
		logger.info("getCount===>");
		do {
			try {
				boolean isOk =false;
				String sDate = dt.format(startDate.plusMinutes(-60));
				String eDate = dt.format(endDate.plusMinutes(60));
				Date currentTime = new Date();
				for (String orgId : orgIds) {
					map.put("ORG_ID", orgId);
					map.put("START_DATE", sDate);//请求开始时间
					map.put("END_DATE", eDate);//请求结束时间
					ApiRequest<Map<String, String>> apiRequest = new ApiRequest<Map<String,String>>();
					apiRequest.setData(map);
					ApiResponse<List<BsWplanForm>> apiResponseOne = this.getData(apiRequest);
//					ApiResponse<List<WmsResponseCommonForm>> sourceApiResponse = rmSendAndGetDataApiService.getDate(docType, map);
//					ApiResponse<List<BsWplanForm>> apiResponseOne = getResponse(null, sourceApiResponse, this, map);
					count += apiResponseOne.getCount();
					if ("S1001000".equals(apiResponseOne.getResultCode())) {
						isOk = true;
					} else {
						isOk = false;
						break;
					}
					resutData.setCount(count);
				}
				if(isOk) {
					if(endDate.isBefore(now)) {
						apiRequestDto.setUpdatedDate(Date.from(endDate.atZone(ZoneId.systemDefault()).toInstant()));
					}else {
						apiRequestDto.setUpdatedDate(currentTime);
					}
					wmsApiRequestCountService.updateByPrimaryKeyNotNull(apiRequestDto);//更新时间
					startDate = startDate.plusMinutes(30);
					endDate = startDate.plusMinutes(30);
				}
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		} while (endDate.isBefore(now));
		return resutData;
	}
}
